package com.weijin.service.RedisService;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author WeiJin
 * @Version 1.0
 * @Date 2025/3/21 9:20
 */
@Service
public class OnlineUserService {

    private static final String KEY = "chat:online_users";
    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 将用户id存到redis并设置过期时间一天
     * @param userId 用户id
     */
    public void userLogin(String userId){
        redisTemplate.opsForSet().add(KEY,userId);
        redisTemplate.expire(KEY,1, TimeUnit.DAYS);
    }

    /**
     * 将用户id从redis移除
     * @param userId 用户id
     */
    public void userLogout(String userId){
        redisTemplate.opsForSet().remove(KEY,userId);
    }

    /**
     * 获取用户列表
     * @return 用户列表
     */
    public Set<String> getUserList(){
        return redisTemplate.opsForSet().members(KEY);
    }
}
